package com.propertypoint.persitence.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

import com.propertypoint.exception.DatabaseException;
import com.propertypoint.presentation.model.Agent;
import com.propertypoint.util.DBUtil;

public class RegistrationDAOImpl implements RegistrationDAO {
	private static final String INSERT_USER = "INSERT INTO AGENT"
			+ "(FIRST_NAME,LAST_NAME,PHONE_NUMBER,EMAIL,ADDRESS,USERNAME,PASSWORD,DOB,ZIP_CODE,GENDER,LICENSE_NO,COMPANY_NAME) VALUES"
			+ "(?,?,?,?,?,?,?,?,?,?,?,?)";

	private static final String UPDATE_USER_PROFILE_PIC="UPDATE AGENT SET profile_picture = ? WHERE USERNAME = ?";
	public void registerAgent(Agent agent) throws Exception {
		Connection con = DBUtil.getDBUtil().getConnection();
		PreparedStatement preparedStatement = con.prepareStatement(INSERT_USER,
				Statement.RETURN_GENERATED_KEYS);

		preparedStatement.setString(1, agent.getFirstName());// FIRST_NAME
		preparedStatement.setString(2, agent.getLastName());// LAST_NAME
		preparedStatement.setString(3, agent.getPhoneNumber());// PHONE_NUMBER
		preparedStatement.setString(4, agent.getEmail());// EMAIL
		preparedStatement.setString(5, agent.getAddress());// ADDRESS
		preparedStatement.setString(6, agent.getUsername());// USERNAME
		preparedStatement.setString(7, agent.getPassword());// PASSWORD
		preparedStatement.setString(8, agent.getDateOfBirth());// DOB
		preparedStatement.setString(9, agent.getZipCode());// ZIP_CODE
		preparedStatement.setString(10, agent.getGender());// GNEDER
		preparedStatement.setString(11, agent.getLicenceNo());// LICENSE_NO
		preparedStatement.setString(12, agent.getCompanyName());// COMPANY_NAME
		try {
			// execute insert SQL stetement
			preparedStatement.executeUpdate();
		} catch (Exception e) {
			preparedStatement.close();
			con.close();
			throw new DatabaseException(e.toString());
		}
		finally {
			preparedStatement.close();
			con.close();
		}

	}
	
	public void updateProfilePicture(Agent agent) throws Exception {
		Connection con = DBUtil.getDBUtil().getConnection();
		PreparedStatement preparedStatement = con.prepareStatement(UPDATE_USER_PROFILE_PIC);

		preparedStatement.setString(1, agent.getPicture()); 
		preparedStatement.setString(2, agent.getUsername()); 
		try {
			// execute insert SQL stetement
			preparedStatement.executeUpdate();
		} catch (Exception e) {
			preparedStatement.close();
			con.close();
			throw new DatabaseException(e.toString());
		}
		finally {
			preparedStatement.close();
			con.close();
		}

	}
}
